﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Resources;
using System.Xml;
using System.Xml.Linq;
using Com.CodePlex.SPC3.SPbAM.Model;

namespace Com.CodePlex.SPC3.SPbAM.Data {

	public class ServerWorkspaceRepository : Repository {

		public void Load(ServerWorkspace serverworkspace, Action<int> ReportProgress) {
			int iterations = 100;
			for (int i = 0; i < iterations; i++) {
				System.Threading.Thread.Sleep(500 / iterations);
				ReportProgress(i + 1);
			}
			XElement root = XDocument.Load(serverworkspace.Filename).Root;
			Load(root, serverworkspace);
		}

		private void Load(XElement parentxmlnode, IServerResourceContainer parent) {
			foreach (XElement xmlnode in parentxmlnode.Elements()) {
				switch (xmlnode.Name.LocalName) {
					case "ServerGroup":
						ServerGroup item = new ServerGroup() {
							Name = xmlnode.Attributes().FirstOrDefault(s => s.Name == "Name").Value
						};
						parent.Children.Add(item);
						Load(xmlnode, item);
						break;
					case "Server":
						parent.Children.Add(new Server() {
							Name = xmlnode.Attribute("Name") != null ? xmlnode.Attribute("Name").Value : null,
							IP = xmlnode.Attribute("IP") != null ? xmlnode.Attribute("IP").Value : null
						});
						break;
				}
			}
		}

		public void Save(ServerWorkspace serverworkspace, string filename, Action<int> ReportProgress) {
			int iterations = 100;
			for (int i = 0; i < iterations; i++) {
				System.Threading.Thread.Sleep(1000 / iterations);
				ReportProgress(i + 1);
			}
		}
	}
}